<template>
  <div class="vocabulary-app" :class="isDarkMode ? 'dark-theme' : 'light-theme'">
    <!-- 头部区域 -->
    <header class="app-header">
      <div class="container">
        <div class="header-content">
          <div class="logo">
            <img src="/src/assets/images/4a3ece7aca9c3eee3c352f9b5ec3e6a8.jpg" alt="Logo" class="logo-img">
            <h1 class="app-title">词汇释义匹配</h1>
          </div>
          <button 
            class="theme-toggle" 
            @click="toggleTheme" 
            aria-label="切换主题"
          >
            <span>{{ isDarkMode ? '☀️' : '🌙' }}</span>
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="container">
        <!-- 词汇本选择 -->
        <div class="book-selector" v-if="!loading || bookList.length > 0">
          <select 
            v-model="selectedBookId" 
            @change="handleBookChange" 
            :disabled="loading"
            class="book-select"
          >
            <option value="">-- 选择词汇本 --</option>
            <option v-for="book in bookList" :key="book.bookId" :value="book.bookId">
              {{ book.bookName }}
            </option>
          </select>
          <span class="error-message" v-if="errorMsg">{{ errorMsg }}</span>
        </div>

        <!-- 加载状态 -->
        <div class="loading-indicator" v-if="loading && bookList.length === 0">
          加载中...请稍候
        </div>

        <!-- 进度指示器 -->
        <div class="progress-tracker" v-if="!loading && selectedBookId">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
          </div>
          <div class="progress-stats">
            <span>进度: {{ completedWords }}/{{ totalWords }}</span>
            <span>正确率: {{ accuracyRate }}%</span>
          </div>
        </div>

        <!-- 单词卡片 -->
        <div class="word-card" v-if="currentWord && !loading && selectedBookId">
          <div class="word-info">
            <h2 class="word">{{ currentWord.word }}</h2>
            <p class="pronunciation">{{ currentWord.pronunciation }}</p>
            <p class="chinese-meaning" v-if="currentWord.chinese"></p>
          </div>
          <p class="prompt">请选择正确的释义：</p>
        </div>

        <!-- 选项列表 -->
        <div class="options-list" v-if="currentOptions.length > 0 && !loading && selectedBookId">
          <div 
            v-for="(option, index) in currentOptions" 
            :key="index" 
            class="option-item"
            :class="{ 
              selected: selectedOption === option.id,
              correct: showFeedback && option.id === currentWord?.id,
              incorrect: showFeedback && selectedOption === option.id && option.id !== currentWord?.id
            }"
            @click="selectOption(option.id)"
            :disabled="isWaiting"
          >
            <div class="option-content">
              <p class="definition">{{ option.chinese }}</p>
              <p class="example">{{ option.example }}</p>
            </div>
            <div class="option-indicator" v-if="showFeedback">
              <span v-if="option.id === currentWord?.id">✓</span>
              <span v-if="selectedOption === option.id && option.id !== currentWord?.id">✗</span>
            </div>
          </div>
        </div>

        <!-- 反馈信息 -->
        <div class="feedback-message" v-if="showFeedback && !loading && selectedBookId">
          <p class="message" :class="{ correct: isCorrect, incorrect: !isCorrect }">
            {{ isCorrect ? '回答正确！即将进入下一个单词...' : '回答错误！2秒后重新出题...' }}
            <span v-if="!isCorrect" class="correct-answer">
              正确答案：{{currentWord.chinese }}
            </span>
          </p>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="!loading && selectedBookId && words.length === 0">
          <p>当前词汇本暂无单词数据，请选择其他词汇本</p>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="app-footer">
      <div class="container">
        <p class="copyright">© 词汇学习，不知名小组。</p>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue';
// 导入封装的API服务
import { vocabularyApi } from '@/views/subjects/english/pages/vocabulary-study/script/vocabulary-js/vocabularyMatching.js';

// 类型定义
interface VocabBook {
  bookId: number;
  bookName: string;
}

interface VocabularyItem {
  id: number;
  word: string;
  pronunciation: string;
  definition: string;
  example?: string;
  chinese?: string;
  bookId?: number;
}

// 状态管理
const isDarkMode = ref(false);
const words = ref<VocabularyItem[]>([]);
const bookList = ref<VocabBook[]>([]);
const selectedBookId = ref<string>('');
const currentWord = ref<VocabularyItem | null>(null);
const currentOptions = ref<VocabularyItem[]>([]);
const selectedOption = ref<number | null>(null);
const showFeedback = ref(false);
const isCorrect = ref(false);
const wordResults = ref<{ id: number; correct: boolean }[]>([]);
const isWaiting = ref(false);
const loading = ref(false);
const errorMsg = ref('');
let timer: ReturnType<typeof setTimeout> | null = null;

// 计算属性
const progressPercentage = computed(() => {
  if (totalWords.value === 0) return 0;
  return (wordResults.value.length / totalWords.value) * 100;
});

const completedWords = computed(() => wordResults.value.length);
const totalWords = computed(() => words.value.length);

const accuracyRate = computed(() => {
  if (wordResults.value.length === 0) return 0;
  const correctCount = wordResults.value.filter(r => r.correct).length;
  return Math.round((correctCount / wordResults.value.length) * 100);
});

// 初始化
onMounted(async () => {
  // 主题初始化
  const savedTheme = localStorage.getItem('vocabTheme');
  if (savedTheme) {
    isDarkMode.value = savedTheme === 'dark';
  }

  // 加载词汇本列表
  try {
    loading.value = true;
    bookList.value = await vocabularyApi.getVocabBooks();
    errorMsg.value = '';
    
    // 默认选择第一个词汇本
    if (bookList.value.length > 0) {
      selectedBookId.value = bookList.value[0].bookId.toString();
    }
  } catch (err) {
    errorMsg.value = err instanceof Error ? err.message : '加载词汇本失败';
  } finally {
    loading.value = false;
  }
});

// 监听词汇本变化
watch(selectedBookId, async (newBookId) => {
  if (newBookId) {
    await loadWordsByBookId(Number(newBookId));
  } else {
    resetLearningState();
  }
});

// 清理定时器
onUnmounted(() => {
  if (timer) clearTimeout(timer);
});

// 加载指定词汇本的单词
const loadWordsByBookId = async (bookId: number) => {
  try {
    loading.value = true;
    errorMsg.value = '';
    
    // 调用封装的API获取单词数据
    const fetchedWords = await vocabularyApi.getWordsByBookId(bookId);
    words.value = [...fetchedWords].sort(() => Math.random() - 0.5);
    
    // 重置学习状态
    resetLearningState();
    
    // 加载第一个单词
    if (words.value.length > 0) {
      loadNextWord();
    }
  } catch (err) {
    errorMsg.value = err instanceof Error ? err.message : '加载单词失败';
    words.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理词汇本选择变化
const handleBookChange = () => {
  // 由watch监听处理
};

// 重置学习状态
const resetLearningState = () => {
  wordResults.value = [];
  currentWord.value = null;
  currentOptions.value = [];
  selectedOption.value = null;
  showFeedback.value = false;
  isCorrect.value = false;
  if (timer) clearTimeout(timer);
};

// 加载下一个单词
const loadNextWord = () => {
  if (timer) clearTimeout(timer);
  
  // 找到未学习的单词
  const unlearned = words.value.filter(word => 
    !wordResults.value.some(r => r.id === word.id)
  );
  
  if (unlearned.length === 0) {
    // 所有单词学习完成
    alert(`学习完成！\n总单词数: ${totalWords.value}\n正确率: ${accuracyRate.value}%`);
    resetLearningState();
    words.value = [...words.value].sort(() => Math.random() - 0.5);
    loadNextWord();
    return;
  }
  
  // 随机选择一个未学习的单词
  const randomIndex = Math.floor(Math.random() * unlearned.length);
  currentWord.value = unlearned[randomIndex];
  
  // 生成选项
  if (currentWord.value) {
    generateOptions(currentWord.value);
  }
  
  // 重置状态
  resetQuestionState();
};

// 生成选项
const generateOptions = (targetWord: VocabularyItem) => {
  // 正确选项
  const correctOption = { ...targetWord };
  
  // 干扰项 - 从同词汇本的其他单词中选择
  const distractors = words.value
    .filter(word => word.id !== targetWord.id)
    .sort(() => Math.random() - 0.5)
    .slice(0, 3); // 最多3个干扰项
  
  // 混合选项并打乱顺序
  currentOptions.value = [correctOption, ...distractors]
    .sort(() => Math.random() - 0.5);
};

// 选择选项
const selectOption = (optionId: number) => {
  if (showFeedback.value || isWaiting.value) return;
  
  selectedOption.value = optionId;
  checkAnswer(optionId);
};

// 检查答案
const checkAnswer = (optionId: number) => {
  if (!currentWord.value) return;
  
  isCorrect.value = optionId === currentWord.value.id;
  showFeedback.value = true;
  
  if (isCorrect.value) {
    // 正确：记录结果，进入下一个单词
    wordResults.value.push({
      id: currentWord.value.id,
      correct: true
    });
    
    timer = setTimeout(loadNextWord, 2000);
  } else {
    // 错误：显示正确答案后重新出题
    isWaiting.value = true;
    timer = setTimeout(() => {
      if (currentWord.value) {
        generateOptions(currentWord.value);
      }
      resetQuestionState();
      isWaiting.value = false;
    }, 2000);
  }
};

// 重置当前题目状态
const resetQuestionState = () => {
  selectedOption.value = null;
  showFeedback.value = false;
  isCorrect.value = false;
};

// 获取正确释义
const getCorrectDefinition = () => {
  return currentWord.value?.definition || '';
};

// 切换主题
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value;
  localStorage.setItem('vocabTheme', isDarkMode.value ? 'dark' : 'light');
};
</script>

<style scoped>
/* 基础样式 */
.vocabulary-app {
  --bg-main: #f0f2f5; /* 主背景灰色 */
  --bg-card: #ffffff; /* 白天主题卡片白色 */
  --bg-accent: #f8f9fa;
  --text-primary: #1a1a1a;
  --text-secondary: #666666;
  --primary-color: #4263eb;
  --correct-color: #28a745;
  --incorrect-color: #dc3545;
  --border-color: #e9ecef;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  min-height: 100vh;
  background-color: var(--bg-main);
  color: var(--text-primary);
  font-family: 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
  line-height: 1.6;
  transition: all 0.3s ease;
}

/* 深色主题 */
.vocabulary-app.dark-theme {
  --bg-main: #121212; /* 深色主背景 */
  --bg-card: #1e1e1e; /* 黑夜主题卡片黑色 */
  --bg-accent: #2d2d2d;
  --text-primary: #f8f9fa;
  --text-secondary: #b3b3b3;
  --border-color: #343a40;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.app-header {
  background-color: var(--bg-card);
  border-bottom: 1px solid var(--border-color);
  padding: 16px 0;
  box-shadow: var(--shadow);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.app-title {
  font-size: 1.2rem;
  margin: 0;
  font-weight: 600;
  color: var(--primary-color);
}

.theme-toggle {
  background: none;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--bg-accent);
  color: var(--text-primary);
  cursor: pointer;
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.theme-toggle:hover {
  background-color: var(--primary-color);
  color: white;
  transform: scale(1.1);
}

/* 词汇本选择器 */
.book-selector {
  margin: 20px 0;
  padding: 15px;
  background-color: var(--bg-card);
  border-radius: 8px;
  box-shadow: var(--shadow);
}

.book-select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-accent);
  color: var(--text-primary);
  font-size: 1rem;
  cursor: pointer;
  transition: border-color 0.2s;
}

.book-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 主内容区 */
.main-content {
  padding: 20px 0 60px;
}

/* 进度跟踪 */
.progress-tracker {
  margin-bottom: 30px;
}

.progress-bar {
  height: 8px;
  background-color: var(--border-color);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background-color: var(--primary-color);
  transition: width 0.5s ease;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  font-size: 0.9rem;
  color: var(--text-secondary);
}

/* 单词卡片 */
.word-card {
  background-color: var(--bg-card);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: var(--shadow);
}

.word-info {
  text-align: center;
  margin-bottom: 15px;
}

.word {
  font-size: 2rem;
  margin: 0 0 10px;
  color: var(--primary-color);
}

.pronunciation {
  color: var(--text-secondary);
  font-style: italic;
  margin: 0 0 8px;
  font-size: 1.1rem;
}

.chinese-meaning {
  color: var(--text-primary);
  margin: 0 0 10px;
  font-size: 1rem;
  font-weight: 500;
}

.prompt {
  margin: 0;
  font-size: 1rem;
  color: var(--text-secondary);
  padding-top: 10px;
  border-top: 1px solid var(--border-color);
}

/* 选项列表 */
.options-list {
  display: grid;
  gap: 15px;
  margin-bottom: 20px;
}

.option-item {
  background-color: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  box-shadow: 0 2px 4px rgba(0,0,0,0.02);
}

.option-item:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.05);
}

.option-item.selected {
  border-color: var(--primary-color);
  background-color: rgba(66, 99, 235, 0.05);
}

.option-item.correct {
  border-color: var(--correct-color);
  background-color: rgba(40, 167, 69, 0.05);
}

.option-item.incorrect {
  border-color: var(--incorrect-color);
  background-color: rgba(220, 53, 69, 0.05);
}

.option-item:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.definition {
  margin: 0 0 8px;
  font-size: 1rem;
  line-height: 1.5;
}

.example {
  margin: 0;
  font-size: 0.85rem;
  color: var(--text-secondary);
  font-style: italic;
}

.option-indicator {
  min-width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-left: 15px;
}

/* 反馈信息 */
.feedback-message {
  padding: 15px;
  border-radius: 8px;
  margin-top: 10px;
  text-align: center;
}

.message {
  margin: 0;
  font-size: 1rem;
  padding: 10px;
  border-radius: 6px;
}

.message.correct {
  background-color: rgba(40, 167, 69, 0.1);
  color: var(--correct-color);
}

.message.incorrect {
  background-color: rgba(220, 53, 69, 0.1);
  color: var(--incorrect-color);
}

.correct-answer {
  display: block;
  margin-top: 8px;
  font-size: 0.9rem;
  padding-top: 8px;
  border-top: 1px dashed currentColor;
}

/* 加载和空状态 */
.loading-indicator {
  text-align: center;
  padding: 40px 0;
  color: var(--text-secondary);
  font-size: 1.1rem;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: var(--text-secondary);
  font-size: 1.1rem;
  background-color: var(--bg-card);
  border-radius: 8px;
  margin-top: 20px;
}

.error-message {
  color: var(--incorrect-color);
  font-size: 0.9rem;
  margin-top: 8px;
  display: block;
}

/* 页脚 */
.app-footer {
  background-color: var(--bg-card);
  border-top: 1px solid var(--border-color);
  padding: 20px 0;
  margin-top: auto;
}

.copyright {
  margin: 0;
  text-align: center;
  font-size: 0.85rem;
  color: var(--text-secondary);
}

/* 响应式调整 */
@media (max-width: 600px) {
  .options-list {
    grid-template-columns: 1fr;
  }
  
  .word {
    font-size: 1.7rem;
  }
}
</style>
    